package com.eduardcapell.lopodder.gui;

import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Vector;

import javax.swing.table.DefaultTableModel;

import com.eduardcapell.lopodder.beans.FeedElement;
import com.eduardcapell.lopodder.db.DBAccess;
import com.eduardcapell.lopodder.misc.Constants;
import com.eduardcapell.lopodder.misc.Utils;

public class FeedContentsTableModel extends DefaultTableModel {

	public static final int COL_NAME = 0;
	public static final int COL_DATE = 1;
	public static final int COL_SIZE = 2;
	public static final int COL_DOWNLOADED = 3;
	
	
	public static final String[] COLUMN_NAMES = {
		"Name", 
		"Date", 
		"Size", 
		"Downloaded"
	};
	
	private List<FeedElement> elements;
	
	public FeedContentsTableModel(List<FeedElement> elements) {
		super();
		this.elements = elements;
		Collections.sort(elements);
	}
	
	@Override
	public Vector getDataVector() {
		return new Vector(elements);
	}

	@Override
	public int getColumnCount() {
		return COLUMN_NAMES.length;
	}

	@Override
	public String getColumnName(int i) {
		return COLUMN_NAMES[i];
	}

	@Override
	public int getRowCount() {
		if (elements == null || elements.size() <= 0) {
			return 0;
		}
		
		return elements.size();
	}
	
	
	@Override
	public Class<?> getColumnClass(int column) {
		switch (column) {
		case COL_DATE:
			return Date.class;
		case COL_DOWNLOADED:
			return Boolean.class;
		case COL_NAME:
		case COL_SIZE:
			return String.class;
		}
		
		return String.class;
	}

	@Override
	public Object getValueAt(int row, int column) {
		if (elements == null || elements.size() <= 0) {
			return 0;
		}
		
		switch (column) {
		case COL_DATE:
			// return Utils.dateTime(elements.get(row).getDate(), Constants.DATETIME_FORMAT);
			return elements.get(row).getDate();
		case COL_NAME:
			return elements.get(row).getName();
		case COL_SIZE:
			return Utils.formatMB(elements.get(row).getSize());
		case COL_DOWNLOADED:
			return elements.get(row).isDownloaded();
		}
		
		return null;
	}

	@Override
	public boolean isCellEditable(int row, int column) {
		switch (column) {
		case COL_DOWNLOADED:
			return true;
		default:
			return false;
		}
	}

	@Override
	public void setValueAt(Object o, int row, int col) {
		switch (col) {
		case COL_DOWNLOADED:
			if (!(o instanceof Boolean)) {
				return;
			}
			Boolean b = (Boolean) o;
			FeedElement fe = elements.get(row);
			fe.setDownloaded(b.booleanValue());

			DBAccess.updateFeedElement(fe);
		}
	}
}
